const http = require('http')
const fs = require('fs')
const url = require('url')
const querystring = require('querystring')
const users = {
  admin: '123456'
}
http.createServer((req, res) => {
  let get, post, path
  if (req.method === 'GET') {
    const {query, pathname} = url.parse(req.url, true)
    get = query
    path = pathname
    complete()
  } else if (req.method === 'POST') {
    path = req.url
    const temp = []
    req.on('data', (chunk) => {
      temp.push(chunk)
    })
    req.on('end', () => {
      const buffer = Buffer.concat(temp).toString()
      post = querystring.parse(buffer)
      complete()
    })
  }
  function complete() {
    if (path === '/login') {
      res.writeHead(200, {'Content-Type': 'text/plain; charset=utf-8'})
      if (users[get.username]) {
        if (users[get.username] === get.password) {
          res.end(JSON.stringify({
            code: 0,
            msg: '登录成功'
          }))
        } else {
          res.end(JSON.stringify({
            code: 1,
            msg: '密码错误'
          }))
        }
      } else {
        res.end(JSON.stringify({
          code: 1,
          msg: '用户不存在'
        }))
      }
    } else if (path === '/register') {
      res.writeHead(200, {'Content-Type': 'text/plain; charset=utf-8'})
      if (users[post.username]) {
        res.end(JSON.stringify({
          code: 1,
          msg: '已注册'
        }))
      } else {
        users[post.username] = post.password
        res.end(JSON.stringify({
          code: 0,
          msg: '注册成功'
        }))
      }
    } else {
      fs.readFile(`html${path}`, (err, data) => {
        if (err) {
          res.end('404')
        } else {
          res.end(data)
        }
      })
    }
  }
}).listen(8888)